package com.example.demo.service;

import com.example.demo.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @program: demo
 * @description:
 * @author: 陈恩涛
 * @create: 2023-06-17 21:49
 **/

@Service
public class TransactionService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private StudentService userService;

    public String doProgrammaticTransaction() {

        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        transactionTemplate.execute( transactionStatus -> {
            try {
                Student student1 = new Student();

                student1.setUserName("张三");
                student1.setScore(99);
                userService.save(student1);

                int i = 10 / 0;

                Student student2 = new Student();
                student2.setUserName("李华");
                student2.setScore(100);
            } catch (Exception e) {
                // 事务回滚
                transactionStatus.setRollbackOnly();
            }

            System.out.println(transactionStatus.isNewTransaction());
            System.out.println(transactionStatus.isCompleted());
            System.out.println(transactionStatus.isRollbackOnly());
            return null;
        });
        System.out.println(transactionTemplate.getPropagationBehavior());
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        return transactionTemplate.getIsolationLevel() +  " \t" + transactionTemplate.getPropagationBehavior();
    }



}
